import json
import time
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo

import pytz
import requests

from product_upload.domain.amazon_us.amazon_us_order import AmazonUsOrder
from product_upload.util.basic.mysql_util import db_list_by_page

# Authentication credentials
CLIENT_ID = "amzn1.application-oa2-client.20b679d990e0416b8373fda0db1de6af"
CLIENT_SECRET = "amzn1.oa2-cs.v1.62fd52b80d7da4aa0a676e4bce88843bb3c14c27fd908c92a726b8b218a9a455"
REDIRECT_URI = "https://www.treatlife.shop"

# API endpoints
AUTH_URL = "https://api.amazon.com/auth/o2/token"
ORDERS_URL = "https://sellingpartnerapi-na.amazon.com/orders/v0/orders"

_token_storage = {}


def format_date_to_iso8601(date_str=None):
    if date_str:
        dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    else:
        dt = datetime.now()
    return dt.strftime("%Y-%m-%dT%H:%M:%S")


def convert_utc_to_beijing_time(utc_date_str):
    utc_dt = datetime.strptime(utc_date_str, "%Y-%m-%dT%H:%M:%SZ")
    utc_dt = utc_dt.replace(tzinfo=timezone.utc)
    beijing_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
    return beijing_dt.strftime("%Y-%m-%d %H:%M:%S")


def beijing_to_pdt(beijing_str):
    beijing_tz = pytz.timezone('Asia/Shanghai')  # 北京时间对应的时区
    beijing_date = datetime.strptime(beijing_str, "%Y-%m-%d %H:%M:%S")  # 解析输入字符串
    beijing_date = beijing_tz.localize(beijing_date)  # 设置为北京时间时区
    pacific_tz = pytz.timezone('America/Los_Angeles')  # 太平洋时区
    pacific_date = beijing_date.astimezone(pacific_tz)  # 转换为太平洋时间
    formatted_time = pacific_date.strftime("%Y-%#m-%#d %#I:%#M %p %Z")
    return formatted_time

def get_amazon_shop_refresh_tokens():
    tokens_tuple = db_list_by_page("sys_config", "config_value", 'config_key = "amazon_shop_refresh_tokens"', None, 1, 10, "config_id")
    _refresh_tokens = json.loads(tokens_tuple[0][0])
    return _refresh_tokens


def get_access_token(shop, refresh_tokens=None):
    current_time = int(time.time())
    if shop in _token_storage and _token_storage[shop].get('token') and current_time < _token_storage[shop].get('expiry', 0):
        return _token_storage[shop]['token']
    if not refresh_tokens:
        refresh_tokens = get_amazon_shop_refresh_tokens().get(shop)
    data = {
        'grant_type': 'refresh_token',
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
        'redirect_uri': REDIRECT_URI,
        'refresh_token': refresh_tokens
    }
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    response = requests.post(AUTH_URL, data=data, headers=headers)
    if response.status_code == 200:
        token_data = response.json()
        _token_storage[shop] = {
            'token': token_data['access_token'],
            'expiry': current_time + token_data['expires_in'] - 480  # 8 minutes buffer
        }
        return _token_storage[shop]['token']
    else:
        print(f"Failed to get access token for {shop}: {response.text}")


def get_orders(shop, created_after, next_token='', marketplace_ids="ATVPDKIKX0DER", fulfillment_channels="MFN", max_results=100):
    params = {
        'CreatedAfter': created_after,
        'MarketplaceIds': marketplace_ids,
        'FulfillmentChannels': fulfillment_channels,
        'MaxResultsPerPage': max_results,
        'NextToken': next_token
    }
    headers = {
        'Accept': 'application/json',
        'x-amz-access-token': get_access_token(shop)
    }
    response = requests.get(ORDERS_URL, params=params, headers=headers)
    if 400 < response.status_code < 500 and "The access token you provided has expired" in response.text:
        if shop in _token_storage:
            del _token_storage[shop]
        refresh_token = get_amazon_shop_refresh_tokens().get(shop)
        headers['x-amz-access-token'] = get_access_token(shop, refresh_token)
        response = requests.get(ORDERS_URL, params=params, headers=headers)
    clear_orders = []
    if response.status_code == 200:
        # 需要进行轮询遍历
        next_token = 'init'
        while next_token:
            if next_token != "init":
                params['NextToken'] = next_token
                response = requests.get(ORDERS_URL, params=params, headers=headers)
            data = response.json()
            if data and data.get("payload"):
                data = data["payload"]
                next_token = data.get("NextToken", "")
                orders = data.get("Orders", [])
                for order in orders:
                    order_id = order.get("AmazonOrderId")
                    earliest_ship_date = convert_utc_to_beijing_time(order.get("EarliestShipDate"))
                    latest_ship_date = convert_utc_to_beijing_time(order.get("LatestShipDate"))
                    purchase_date = convert_utc_to_beijing_time(order.get("PurchaseDate"))
                    order_status = order.get("OrderStatus")
                    order_type = order.get("OrderType")
                    amount = order.get("OrderTotal").get("Amount")
                    is_replace = 1 if order.get("IsReplacementOrder") else 0
                    clear_orders.append([order_id, order_status, order_type, amount, is_replace, purchase_date, earliest_ship_date, latest_ship_date, json.dumps(order)])
        return clear_orders
    else:
        print(f"Failed to get orders for {shop}: {response.text}")
        # 被封禁的账号 忽略
        return None


def fetch_amazon_us_order():
    is_start_rpa = False
    shops = get_amazon_shop_refresh_tokens().keys()
    # 查询
    two_weeks_ago = datetime.now() - timedelta(days=14)
    # 格式化为目标字符串
    after_date = two_weeks_ago.strftime("%Y-%m-%dT%H:%M:%S")
    for shop in shops:
        create_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        orders = get_orders(shop, after_date)
        if orders:
            #[order_id, order_status, order_type, amount, is_replace, purchase_date, earliest_ship_date, latest_ship_date, json.dumps(order)]
            order_id_str = ','.join([f'"{x[0]}"' for x in orders])
            api_order_map = {x[0]: x for x in orders}
            db_order_list = db_list_by_page("amazon_us_order", "id,order_id,order,order_status,order_type,is_replacement", f'order_id in ({order_id_str})', AmazonUsOrder,1,9999)
            db_order_map = {x.order_id : x for x in db_order_list}
            insert_order_id = list(set(api_order_map.keys()) - set(db_order_map.keys()))
            update_order_id = list(set(api_order_map.keys()) & set(db_order_map.keys()))
            insert_order = []
            update_order = []
            for order_id in insert_order_id:
                api_order = api_order_map[order_id]
                api_order.extend([shop,create_time])
                insert_order.append(api_order)
                is_start_rpa = True
            for order_id in update_order_id:
                db_order = db_order_map[order_id]
                api_order = api_order_map[order_id]
                if db_order.order_status != api_order[1] or db_order.order_type != api_order[2] or db_order.is_replacement != api_order[4]:
                    update_order.append([db_order.id, api_order[1], api_order[2], api_order[4]])
                    # 由已付款但未发货变为取消,需要通知一下
                    if db_order.order_status == "Unshipped" and api_order[1] == "Canceled":
                        pass



if __name__ == '__main__':
    # Example usage
    for i in list(set()):
        print(i)
    #print(beijing_to_pdt(convert_utc_to_beijing_time("2025-03-26T00:27:23Z")))
    pass
    # shop_name = "shop1"  # 使用哪个店铺
    # created_after = "2025-04-01T00:00:00"
    #
    # try:
    #     orders = get_orders(shop=shop_name, created_after=created_after)
    #     print(json.dumps(orders, indent=2))
    # except Exception as e:
    #     print(f"Error getting orders: {e}")
